<?php

declare(strict_types=1);

namespace App\AdminApi\Modular\Data\Service;

use App\Common\Modular\Data\Model\ResourceModel;
use App\Common\Modular\Data\Serve\ResourceServe;
use Core\Service\Uploader;
use Exception;
use League\Flysystem\FilesystemException;

/**
 * 资源服务层
 * Class BannerService
 */
class ResourcesService extends ResourceServe
{


    /**
     * 删除资源
     * @param array $where
     * @return int
     */
    public function removeResources(array $where): int
    {
        $resources = $this->search($where)->get();
        if (count($resources) === 0) {
            return 0;
        }
        $success = 0;
        /**
         * @var ResourceModel $item
         */
        $uploader = container(Uploader::class);
        foreach ($resources as $item) {
            try {
                $uploader->drive($item->drive)->delete($item->path);
                $item->delete();
                $success++;
            } catch (Exception|FilesystemException $exception) {
                logger('exceptions', 'upload')->error($exception->getMessage(), [
                    'exceptions' => ['file' => $exception->getFile(), 'line' => $exception->getLine(), 'class' => $exception::class]
                ]);
                continue;
            }
        }
        return $success;
    }
}